package com.basic.nio.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @Author: wisdom
 * @Date: 2024/3/31  1:47 PM
 * @Description:
 */
public class Server {

    public static void main(String[] args) throws IOException {
        //获取服务端socket通道
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //绑定端口
        socketChannel.bind(new InetSocketAddress(8080));
        //非阻塞模式
        socketChannel.configureBlocking(false);
        //获取选择器
        Selector selector = Selector.open();
        //通道注册到选择器，并且指定监听事件
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //Selector轮询绑定的事件
        while (selector.select() > 0){
            System.out.println("开始一轮事件处理~~~");
            //获取选择器所有注册的通道
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                //接受事件
                if(selectionKey.isAcceptable()){
                    SocketChannel channel = socketChannel.accept();
                    channel.configureBlocking(false);
                    //客户端注册到selector
                    channel.register(selector,SelectionKey.OP_READ);
                } else if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel)selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len;
                    while ((len = channel.read(buffer)) > 0){
                        buffer.flip();
                        System.out.println(new String(buffer.array(),buffer.position(),len));
                        buffer.clear();
                    }
                }
                //处理完毕移除当前事件
                iterator.remove();
            }
        }
    }


}
